package com.rasenhund.android.grecorder.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.rasenhund.android.grecorder.R;
import com.rasenhund.android.grecorder.common.Const;
import com.rasenhund.android.grecorder.dao.RecordDao;
import com.rasenhund.android.grecorder.helper.DbHelper;
import com.rasenhund.android.grecorder.schema.Record;

/**
 * 履歴詳細、編集画面
 */
public class HistoryDetailActivity extends BaseActivity {
    // public class HistoryDetailActivity extends FragmentActivity {
    @SuppressWarnings("unused")
    private static final String TAG = HistoryDetailActivity.class.getSimpleName();
    private final HistoryDetailActivity self = this;

    static final int DIALOG_DELETE_CONFIRM = 1;

    static final int MODE_DETAIL_VIEW = 1; // 表示モード
    static final int MODE_DETAIL_EDIT = 2; // 編集モード

    Record mRecord = null;
    int mMode = MODE_DETAIL_VIEW;

    TextView mTextMemoView = null;
    EditText mTextMemoEdit = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.history_detail);

        Intent intent = getIntent();
        long lRowId = intent.getLongExtra(Const.KEY.KEY_ROWID, -1);

        if (lRowId != -1) {

            DbHelper dbHelper = new DbHelper(self);
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            RecordDao dao = new RecordDao(db);

            mRecord = dao.selectAt((int) lRowId);

            db.close();

            if (mRecord == null) {
                finish();
            }

        }

        TextView txtDate = (TextView) findViewById(R.id.txtDate);
        txtDate.setText(mRecord.getInsertDate());

        TextView txtStage = (TextView) findViewById(R.id.txtStage);
        txtStage.setText(Const.getStageNm(self, mRecord.getStageCd()));

        TextView txtCategory = (TextView) findViewById(R.id.txtCategory);
        txtCategory.setText(Const.getCategoryNm(self,
                mRecord.getCategoryCd()));

        TextView txtResult = (TextView) findViewById(R.id.txtResult);
        txtResult.setText(Const.getResultNm(self, mRecord.getResultCd()));

        mTextMemoView = (TextView) findViewById(R.id.txtMemoView);
        mTextMemoView.setText(mRecord.getMemo());

        mTextMemoEdit = (EditText) findViewById(R.id.txtMemoEdit);
        mTextMemoEdit.setText(mRecord.getMemo());

        ImageButton btnEditSave = (ImageButton) findViewById(R.id.btnEditSave);
        btnEditSave.setOnClickListener(btnEditSave_OnClickListener);

        ImageButton btnDelete = (ImageButton) findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(btnDelete_OnClickListener);

    }

    @Override
    protected Dialog onCreateDialog(int id) {

        switch (id) {
            case DIALOG_DELETE_CONFIRM:

                AlertDialog.Builder builder = null;
                builder = new AlertDialog.Builder(self);
                builder.setMessage(getStr(R.string.msg_confirm_delete));
                builder.setPositiveButton(getStr(R.string.msg_yes),
                        deleteConfirm_PositiveButton_OnClickListener);
                builder.setNegativeButton(getStr(R.string.msg_no),
                        deleteConfirm_NegativeButton_OnClickListener);

                return builder.create();

        }

        return null;

    }

    /********************
     * EventListener
     ********************/
    /**
     * 編集／保存ボタン押下時のイベントリスナ
     */
    private final OnClickListener btnEditSave_OnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            switch (mMode) {
                case MODE_DETAIL_VIEW: // 表示モード

                    // EditTextを可視化し編集モードへ移行
                    
                    mTextMemoView.setVisibility(View.GONE);
                    mTextMemoEdit.setVisibility(View.VISIBLE);

                    ImageButton btnEditSave = (ImageButton) findViewById(R.id.btnEditSave);
                    btnEditSave.setImageResource(android.R.drawable.ic_menu_save);

                    mMode = MODE_DETAIL_EDIT;

                    break;

                case MODE_DETAIL_EDIT: // 編集モード

                    // 更新処理を実行
                    if (update()) {
                        String sMsg = getStr(R.string.msg_save_complete);
                        Toast.makeText(self, sMsg, Toast.LENGTH_SHORT).show();

                        finish();

                    }

                    break;

            }

        }
        
    };

    /**
     * 削除ボタン押下時のイベントリスナ
     */
    private final OnClickListener btnDelete_OnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            showDialog(DIALOG_DELETE_CONFIRM);

        }

    };

    /**
     * 削除確認ダイアログ OKボタン押下時のイベントリスナ
     */
    private final DialogInterface.OnClickListener deleteConfirm_PositiveButton_OnClickListener = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            // 削除処理を実行
            if (mRecord != null) {
                if (deleteAt((int) mRecord.getRowId())) {
                    String sMsg = getStr(R.string.msg_delete_complete);
                    Toast.makeText(self, sMsg, Toast.LENGTH_SHORT).show();

                    finish();
                }
            }

        }
    };

    /**
     * 削除確認ダイアログ キャンセルボタン押下時のイベントリスナ
     */
    private final DialogInterface.OnClickListener deleteConfirm_NegativeButton_OnClickListener = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            // ダイアログのキャンセル
            dialog.cancel();

        }
    };

    /********************
     * Method
     ********************/

    /**
     * 更新処理
     */
    private boolean update() {

        String sMemo = mTextMemoEdit.getText().toString();

        DbHelper dbHelper = null;
        SQLiteDatabase db = null;

        int iRet;

        try {

            dbHelper = new DbHelper(self);
            db = dbHelper.getWritableDatabase();
            RecordDao dao = new RecordDao(db);

            mRecord.setMemo(sMemo);
            iRet = dao.update(mRecord);

        } finally {
            if (db.isOpen()) {
                db.close();
            }
        }

        if (iRet == 0) {
            return false;
        }

        return true;

    }

    /**
     * 削除処理
     * 
     * @param rowId
     */
    private Boolean deleteAt(int rowId) {

        DbHelper dbHelper = null;
        SQLiteDatabase db = null;

        int iRet;

        try {

            dbHelper = new DbHelper(self);
            db = dbHelper.getWritableDatabase();
            RecordDao dao = new RecordDao(db);

            iRet = dao.deleteAt(rowId);

        } finally {
            if (db.isOpen()) {
                db.close();
            }
        }

        if (iRet == 0) {
            return false;
        }

        return true;

    }

}
